package service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import constant.Constant;
import dao.ResourceDao;
import entity.Resource;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.ResourceService;
import vo.ResourceVo;

import java.util.Date;
import java.util.List;

@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    ResourceDao resourceDao;

    // 添加资源
    @Override
    public boolean addFrontResource(Resource resource) throws ServiceException {
//        查询标题是否可用
        if (null != resourceDao.selectResourceByTitle(resource.getTitle())) {
            throw new ServiceException("该标题已存在！");
        }

//        添加资源
        resource.setCreate_date(new Date());
        resource.setStatus(Constant.STATUS_ENABLE);
        System.out.println(resource);
        return 1 == resourceDao.insertResource(resource) ? true : false;
    }

    @Override
    public PageInfo<Resource> queryResource(Integer pageNo, ResourceVo resource) {
        System.out.println("kaishi");
        PageHelper.startPage(pageNo, Constant.PAGE_SIZE);
        List<Resource> list = resourceDao.selectResources(resource);
        if (null == list) {
            throw new ServiceException("暂无数据");
        }
        System.out.println("jieshu ");
        return new PageInfo<Resource>(list);
    }

    //    前台修改资源
    @Override
    public boolean modifyFrontResource(Resource resource) throws ServiceException {
//        查询标题是否可用
        Resource oldResource = resourceDao.selectResourceByTitle(resource.getTitle());
        if (null != oldResource && resource.getId()!= oldResource.getId()) {
            throw new ServiceException("该标题已存在！");
        }

//        修改资源
        resource.setStatus(Constant.STATUS_ENABLE);
        return 1 == resourceDao.updateResource(resource) ? true : false;
    }

    //    前台删除资源
    @Override
    public boolean removeFrontResource(Integer id) throws ServiceException {
        return 1 == resourceDao.deleteResourceById(id) ? true : false;
    }

    @Override
    public Resource selectById(int id) throws ServiceException {
        return resourceDao.selectById(id);
    }

    @Override
    public int selectClickCountById(int id) throws ServiceException {
        return resourceDao.selectClickCountById(id);
    }

    @Override
    public Boolean updateClickCountById(int id,int click_count) throws ServiceException {
        int result = resourceDao.updateClickCountById(id,click_count);
        return result>0?true:false;
    }
}
